﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using ArunimaErp.Domain;
using ArunimaErp.Models;

namespace ArunimaErp.Controllers
{
    public class StyleController : Controller
    {
        private arunimaEntities db = new arunimaEntities();

        UserAccountRepository userAccountRepository = new UserAccountRepository();

        //
        // GET: /Style/

        [Authorize]
        public ViewResult Index()
        {
            //int AccountId = userAccountRepository.GetAccouctId(User.Identity.Name);
            //var allStyles = db.styleinfo.Where(u => u.AccountId == AccountId).Distinct();

            var allStyles = db.styleinfo.ToList();
            return View(allStyles);
        }

        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table.
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {
            int AccountId = userAccountRepository.GetAccouctId(User.Identity.Name);
            var allStyles = db.styleinfo.Where(u => u.AccountId == AccountId).Distinct();

            IEnumerable<styleinfo> filteredStyles;

            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                filteredStyles = db.styleinfo.Where(u => u.AccountId == userAccountRepository.GetAccouctId(User.Identity.Name)).Distinct()
                   .Where(c => c.StyleNo.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               c.StyleDescription.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               c.Capacity.ToString().Contains(param.sSearch.ToLower())
                   );
            }
            else
            {
                filteredStyles = allStyles;
            }

            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<styleinfo, string> orderingFunction = (c => sortColumnIndex == 1 ? c.StyleNo : "");

            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredStyles = filteredStyles.OrderBy(orderingFunction);
            else
                filteredStyles = filteredStyles.OrderByDescending(orderingFunction);

            var displayedStyles = filteredStyles.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from s in displayedStyles
                         select new[] {
                            Convert.ToString(s.StyleId),
                            s.StyleNo, s.StyleDescription, s.Capacity.ToString()
                };
            return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = allStyles.Count(),
                    iTotalDisplayRecords = filteredStyles.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Style/Create

        public ActionResult Create()
        {
            ViewBag.DevisionId = new SelectList(db.devision, "DevisionId", "DevisionName");
            ViewBag.BuyerId = new SelectList(db.buyerinfo, "BuyerId", "BuyerName");
            ViewBag.CustomerId = new SelectList(db.customerinfo, "CustomerId", "CustomerName");

            return View();
        }

        //
        // POST: /Style/Create

        [HttpPost]
        public ActionResult Create(styleinfo styleinfo)
        {
            if (ModelState.IsValid)
            {
                var check = db.styleinfo.Where(x => x.StyleNo == styleinfo.StyleNo).ToList();
                if (check.Count == 0)
                {
                    int AccountId = userAccountRepository.GetAccouctId(User.Identity.Name);

                    styleinfo.AccountId = AccountId;

                    db.styleinfo.Add(styleinfo);
                    db.SaveChanges();

                    return Json(JsonResponseFactory.SuccessResponse(styleinfo), JsonRequestBehavior.DenyGet);
                }
                else
                {
                    ModelState.AddModelError("StyleNo", "Already Exists");
                }
            }

            var errorList = (from item in ModelState.Values
                             from error in item.Errors
                             select error.ErrorMessage).ToList();

            return Json(JsonResponseFactory.ErrorResponse(errorList), JsonRequestBehavior.DenyGet);  
        }

        //
        // GET: /Style/Edit/5

        public ActionResult Edit(long id)
        {
            styleinfo styleinfo = db.styleinfo.Single(s => s.StyleId == id);

            ViewBag.DevisionId = new SelectList(db.devision, "DevisionId", "DevisionName", styleinfo.DevisionId);
            ViewBag.BuyerId = new SelectList(db.buyerinfo, "BuyerId", "BuyerName", styleinfo.BuyerId);
            ViewBag.CustomerId = new SelectList(db.customerinfo, "CustomerId", "CustomerName", styleinfo.CustomerId);

            return View(styleinfo);
        }

        //
        // POST: /Style/Edit/5

        [HttpPost]
        public JsonResult Edit(styleinfo styleinfo)
        {
            if (ModelState.IsValid)
            {
                var check = db.styleinfo.Where(x => x.StyleNo == styleinfo.StyleNo && x.StyleId != styleinfo.StyleId).ToList();
                if (check.Count == 0)
                {
                    db.styleinfo.Attach(styleinfo);
                    db.Entry(styleinfo).State = EntityState.Modified;
                    db.SaveChanges();

                    return Json(JsonResponseFactory.SuccessResponse(styleinfo), JsonRequestBehavior.DenyGet);
                }
                else
                {
                    ModelState.AddModelError("StyleNo", "Already Exists");
                }
            }

            var errorList = (from item in ModelState.Values
                             from error in item.Errors
                             select error.ErrorMessage).ToList();

            return Json(JsonResponseFactory.ErrorResponse(errorList), JsonRequestBehavior.DenyGet);   
        }

        //
        // GET: /Style/Delete/5

        public ActionResult Delete(long id)
        {
            styleinfo styleinfo = db.styleinfo.Single(s => s.StyleId == id);
            return View(styleinfo);
        }

        //
        // POST: /Style/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            styleinfo styleinfo = db.styleinfo.Single(s => s.StyleId == id);
            db.styleinfo.Remove(styleinfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}